package com.lz.sports.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lz.comm.image.GlideApp
import com.lz.library.dialog.BaseDialogFragment
import com.lz.library.extension.APP
import com.lz.library.extension.getScreenPoint
import com.lz.sports.R
import com.lz.sports.bean.Examinee
import com.lz.sports.core.ProjectManager
import com.lz.sports.databinding.DialogSignSuccessBinding
import com.lz.sports.db.ExamineeDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

//签到成功
class SignSuccessDialog : BaseDialogFragment<DialogSignSuccessBinding>() {

    companion object {
        //延时关闭时间
        const val DELAY_DISMISS = 5000L

        fun show(activity: FragmentActivity, examinee: Examinee): SignSuccessDialog {
            val dialog = SignSuccessDialog().also {
                it.arguments = Bundle().apply { putParcelable("examinee", examinee) }
            }
            dialog.setFrom(true)
            dialog.show(activity.supportFragmentManager)
            return dialog
        }

        fun show(fragment: Fragment, examinee: Examinee): SignSuccessDialog {
            val dialog = SignSuccessDialog().also {
                it.arguments = Bundle().apply { putParcelable("examinee", examinee) }
            }
            dialog.show(fragment.childFragmentManager)
            return dialog
        }
    }

    override fun getLayoutRes(): Int = R.layout.dialog_sign_success

    override fun initData(v: View, savedState: Bundle?) {
        val examinee: Examinee = arguments!!.getParcelable("examinee")!!
        binding.examinee = examinee
        lifecycleScope.launch {
            val job = async(Dispatchers.Default) {
                ExamineeDatabase.get().examResultList(
                    ProjectManager.examPlanId(), ProjectManager.examAreaId(),
                    ProjectManager.examSiteId(), examinee.id
                )
            }
            job.await().forEach {
                val v = layoutInflater.inflate(R.layout.item_sign_project, binding.llContent, false)
                val tv: TextView = v.findViewById(R.id.tv_name)
                tv.text = it.projectName
                binding.llContent.addView(v)
            }
            GlideApp.with(this@SignSuccessDialog).load(examinee.examPhotoFile()).into(binding.ivHead)
            delay(DELAY_DISMISS)
            dismiss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = object : BaseDialog(requireContext()) {
        override fun initParams(params: WindowManager.LayoutParams) {
            params.width = (APP.getScreenPoint().x * 0.9f).toInt()
        }
    }
}